package com.itheima.appserver.Service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.excepiton.ErrorResult;
import com.itheima.appserver.excepiton.MyException;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.pojo.User;
import com.itheima.dubbo.interfaces.UserAPI;
import com.sun.org.apache.bcel.internal.classfile.ConstantString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Reference
    private UserAPI userAPI;

    public void sendLoginMsg(String phone) {
        //判断手机号格式是否正确
        boolean mobile = Validator.isMobile(phone);
        System.out.println(mobile);
        //如果不正确返回错误
        if (!mobile) {
            throw new MyException(ErrorResult.phoneNumError());
        }

        //判断这个人5分钟之内有没有发送过验证码
        String code = redisTemplate.opsForValue().get(Constants.SMS_CODE + phone);
        if (!StrUtil.isBlank(code)) {
            // 之前发送过验证码
            throw new MyException(ErrorResult.sendCodeError());
        }

        //发送验证码，调用阿里云
        String randomCode = "123456";

        //将验证码发送到redis中，保留5分钟
        redisTemplate.opsForValue().set(Constants.SMS_CODE + phone, randomCode, 5, TimeUnit.MINUTES);

    }

    public Map loginVerification(String phone, String verificationCode) {
        //判断手机号是否合法
        boolean mobile = Validator.isMobile(phone);
        System.out.println(mobile);
        //如果不正确返回错误
        if (!mobile) {
            throw new MyException(ErrorResult.phoneNumError());
        }
        //判断验证码是否正确
        String code = redisTemplate.opsForValue().get(Constants.SMS_CODE + phone);
        if (null==code||verificationCode==null||!code.endsWith(verificationCode)){
            throw  new MyException(ErrorResult.verificationCodeError());
        }
        //删除验证码
        Boolean delete = redisTemplate.delete(Constants.SMS_CODE + phone);
        System.out.println("删除代码成果与否"+delete);

        //判断是否为新用户，新用户创建
        User user = userAPI.findUserByPhoneNum(phone);
        boolean shiFouWeiNew = ObjectUtil.isNull(user);

        //默认为老用户
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("isNew", false);
        //判断是否为新用户，新用户创建
        if(!shiFouWeiNew){
            System.out.println("是新用户");
            //调用接口将用户添加到数据库
            userAPI.insertNewUser(User.builder()
                    .mobile(phone).password(SecureUtil.md5(Constants.INIT_PASSWORD))
                    .created(new Date()).updated(new Date())
                    .build());
            hashMap.put("isNew",true);
        }else {
            System.out.println("是老用户");
        }

        //生成token
        Map<String, Object> map = new HashMap<>();
        map.put("uid", user.getId());
        map.put("phoneNum", user.getMobile());
        //设置token过期时间为一周
map.put(JWTPayload.EXPIRES_AT,DateTime.of(System.currentTimeMillis()+Constants.JWT_TIME_OUT));
        String token = JWTUtil.createToken(map, Constants.JWT_SECRET.getBytes());
        //将token添加到map中
        hashMap.put("token",token);
        return hashMap;

    }
}
